package tts.controller.groups;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.GroupsHome;
import tts.dao.UsersHome;
import tts.model.Groups;
import tts.model.Users;

public class Edit extends RedirectAction{

	//fields
	private static final long serialVersionUID = 7369203581207143122L;
	@Autowired
	private UsersHome usersHome;
	@Autowired
	private GroupsHome groupsHome;
	private String groupName;
	private Groups groupEdit;
	private ArrayList<String> strings;

	//get & set
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}	
	public Groups getGroupEdit() {
		return groupEdit;
	}
	public void setGroupEdit(Groups groupEdit) {
		this.groupEdit = groupEdit;
	}
	public ArrayList<String> getStrings() {
		return strings;
	}
	public void setStrings(ArrayList<String> strings) {
		this.strings = strings;
	}

	//methods
	public String edit() {
		try {
			groupEdit.getUsersList().clear();
			for (String s : strings) {
				Users user = usersHome.findByUsername(s);
				this.groupEdit.getUsersList().add(user);
			}
			Collection<Users> allUsers = usersHome.findAll();
			for (Users userAll : allUsers) {
				if (strings.contains(userAll.getUsername())) {
					if (!(userAll.getGroupsList().contains(groupsHome.findByGroupName(this.groupName))))
						userAll.getGroupsList().add(groupsHome.findByGroupName(this.groupName));
				} else if (userAll.getGroupsList().contains(groupsHome.findByGroupName(this.groupName)))
					userAll.getGroupsList().remove(groupsHome.findByGroupName(this.groupName));
			}
			groupsHome.update(this.groupName, this.groupEdit);
		} catch (RuntimeException e) {
			addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("group.updated"));
		return SUCCESS;
	}
}